/*
 * Copyright © 2020-2021 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springboot.druid.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import lombok.SneakyThrows;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * Druid加密工具类。
 * <p>
 * 加解密规则：
 * 明文密码+私钥(privateKey)加密=加密密码;
 * 加密密码+公钥(publicKey)解密=明文密码.
 * </p>
 *
 * @author Denvie
 * @date 2021/7/6
 * @since 1.0.0
 */
public final class DruidEncryptUtils {
    private static String privateKey;
    private static String publicKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.printf("privateKey-->%s%n", privateKey);
            publicKey = keyPair[1];
            System.out.printf("publicKey-->%s%n", publicKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    private DruidEncryptUtils() {
    }

    /**
     * 加密。
     */
    @SneakyThrows
    public static String encrypt(String plainText) {
        System.out.println("明文字符串：" + plainText);
        String cipherTxt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("加密后字符串：" + cipherTxt);
        return cipherTxt;
    }

    /**
     * 解密。
     */
    @SneakyThrows
    public static String decrypt(String cipherText) {
        System.out.println("加密字符串：" + cipherText);
        String plainText = ConfigTools.decrypt(publicKey, cipherText);
        System.out.println("解密后的字符串：" + plainText);
        return plainText;
    }

    public static void main(String[] args) {
        String pwd = encrypt("root");
        decrypt(pwd);
    }
}
